﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetMVC.DTO;
using DotNetMVC.IService;
using DotNetMVC.Model;
using DotNetMVC.Website.Areas.WebAdmin.Filters;
using DotNetMVC.Common;
using DotNetMVC.Website.Areas.WebAdmin.Common;

namespace DotNetMVC.Website.Areas.WebAdmin.Controllers
{
    public class PermissionController : Controller
    {
        public IPermissionService permissionService { get; set; }
        // GET: WebAdmin/Permission
        [AdminAuthorize(IsCheck = true)]
        public ActionResult List()
        {
            List<PermissionDTO> model = permissionService.GetPermissionsByLevel();
            return View(model);
        }

        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Add()
        {
            ViewBag.SelectListHttpMethod = new SelectList(new string[] { "GET", "POST", "GET/POST" });
            
            #region 上级权限
            List<SelectListItem> listPrentPermission = new List<SelectListItem>();
            listPrentPermission.Add(new SelectListItem { Value = "0", Text = "一级权限" });
            foreach (PermissionDTO dto in permissionService.GetPermissionsByLevel(3))
            {
                SelectListItem listItem = new SelectListItem();
                for (int i = 0; i < dto.PermissionLevel; i++)
                {
                    dto.Name = "|-" + dto.Name;
                }
                listItem.Text = dto.Name;
                listItem.Value = dto.Id.ToString();
                listItem.Selected = false;
                listPrentPermission.Add(listItem);
            }
            ViewBag.ListPrentPermission = listPrentPermission;
            #endregion

            #region 是否是菜单
            List<SelectListItem> listIsMenu = new List<SelectListItem>();
            listIsMenu.Add(new SelectListItem { Value = "0", Text = "否" });
            listIsMenu.Add(new SelectListItem { Value = "1", Text = "是" });
            ViewBag.ListIsMenu = listIsMenu;
            #endregion

            return View();
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        [ValidateInput(false)]
        public ActionResult Add(long parentPermission,string name,int isMenu,string menuIcon,string description, string controllerName,string actionName,string httpMethod)
        {
            PermissionDTO modelParentPermission = permissionService.GetDTOById(parentPermission);
            if (string.IsNullOrEmpty(name))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "权限名称不能为空" });
            }
            if (permissionService.Exist(name))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "权限名称已存在" });
            }
            if (string.IsNullOrEmpty(controllerName))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "控制器名称不能为空" });
            }
            if (string.IsNullOrEmpty(actionName))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "Action名称不能为空" });
            }
            if (string.IsNullOrEmpty(httpMethod))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "请选择请求方式" });
            }
            permissionService.Add(modelParentPermission, name, isMenu==1,  menuIcon , description,  controllerName,  actionName,  httpMethod);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "新增权限:" + name);

            return Json(new AjaxResult { Status = "ok" });
            //return View();
        }

        [HttpGet]
        public string Exist(string Name)
        {
            //remote:远程地址只能输出 "true" 或 "false"，不能有其他输出。
            //存在： "false"
            return permissionService.Exist(Name) ? "false":"true"  ;
        }

        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Edit(long id)
        {
            PermissionDTO model = permissionService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到权限信息");
            }
            ViewBag.SelectListHttpMethod = new SelectList(new string[] { "GET", "POST", "GET/POST" }, model.HttpMethod);
            
            #region 上级权限
            List<SelectListItem> listPrentPermission = new List<SelectListItem>();
            listPrentPermission.Add(new SelectListItem { Value = "0", Text = "一级权限" });
            foreach (PermissionDTO dto in permissionService.GetPermissionsByLevel(3))
            {
                SelectListItem listItem = new SelectListItem();
                for (int i = 0; i < dto.PermissionLevel; i++)
                {
                    dto.Name = "|-" + dto.Name;
                }
                listItem.Text = dto.Name;
                listItem.Value = dto.Id.ToString();
                listItem.Selected = false;
                listPrentPermission.Add(listItem);
            }
            ViewBag.ListPrentPermission = listPrentPermission;
            #endregion

            #region 是否是菜单
            List<SelectListItem> listIsMenu = new List<SelectListItem>();
            listIsMenu.Add(new SelectListItem { Value = "0", Text = "否" });
            listIsMenu.Add(new SelectListItem { Value = "1", Text = "是" });
            ViewBag.ListIsMenu = listIsMenu;
            #endregion

            return View(model);
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        [ValidateInput(false)]
        public ActionResult Edit(long id, long parentPermission, string name, int isMenu, string menuIcon, string description, string controllerName, string actionName, string httpMethod)
        {
            PermissionDTO modelParentPermission = permissionService.GetDTOById(parentPermission);
            if (string.IsNullOrEmpty(name))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "权限名称不能为空" });
            }
            if (string.IsNullOrEmpty(controllerName))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "控制器名称不能为空" });
            }
            if (string.IsNullOrEmpty(actionName))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "Action名称不能为空" });
            }
            if (string.IsNullOrEmpty(httpMethod))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "请选择请求方式" });
            }
            Permission model = permissionService.GetById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "权限信息不存在" });
            }
            permissionService.Update(id, modelParentPermission, name, isMenu == 1, menuIcon, description, controllerName, actionName, httpMethod);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "修改权限:" + name+"（Id:"+ id + "）");

            return Json(new AjaxResult { Status = "ok" });
        }


        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Delete(long id)
        {
            PermissionDTO model = permissionService.GetDTOById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error",ErrorMsg= "获取不到权限信息" });
            }
            permissionService.MarkDeleted(id);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "删除权限" + model.Name + "（Id:" + id + "）");
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult BatchDelete(long[] selectdIds)
        {
            if (selectdIds.Length <= 0)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "未选中删除数据" });
            }

            List<long> list = new List<long>();
            foreach (long id in selectdIds)
            {
                list.Add(id);
            }
            permissionService.BatchMarkDeleted(list);

            //操作日志
            AdminHelper.AddUserLog(HttpContext, "批量删除权限（Ids:" + string.Join(",", list) + "）");

            return Json(new AjaxResult { Status = "ok" });
        }
    }
}